﻿#region Class Header
/* ========================================================================
* 【本类功能概述】
* 
* 作者：chinesedragon 
* 时间：5/1/2013 2:53:03 PM
* 文件名：FormRelease
* 版本：V1.0.1
*
* 修改时间： 
* 修改说明：
* ========================================================================
*/
#endregion


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Publisher
{
    /// <summary>
    /// 暂时不实现HTTP上传方式
    /// </summary>
    public partial class FormRelease : FormBase
    {
        private ProjectInfoClass proInfo;
        private ReleaseList releaseList;
        private string publishPath;
        private long fileTotalSize = 0;
        private long uploadSize = 0;
        private int releaseMethod = 0;  //发布方法：0不发布，1本地，2HTTP，3FTP，4WindowsShare
        private BackgroundWorker worker = null;
        string url;
        string user;
        string pwd;

        public FormRelease(ProjectInfoClass pInfo, ReleaseList rList)
        {
            InitializeComponent();
            radioNone.Checked = true;
            EnableLocation = false;
            VisibleBrowse = false;
            VisibleUserPasswrod = false;
            proInfo = pInfo;
            releaseList = rList;

            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.ProgressChanged += worker_ProgressBar;
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_WorkCompleted;
        }

        private bool EnableLocation
        {
            set
            {
                txtLocation.Text = string.Empty;
                txtLocation.Enabled = value;
            }
        }
        private bool VisibleBrowse
        {
            set
            {
                btnBrowse.Visible = value;
            }
        }
        private bool VisibleUserPasswrod
        {
            set
            {
                txtUserName.Text = string.Empty;
                txtPassword.Text = string.Empty;
                labelUser.Visible = value;
                txtUserName.Visible = value;
                labelPassword.Visible = value;
                txtPassword.Visible = value;
            }
        }

        private void RadioButton_CheckeChanged(object sender, EventArgs e)
        {
            RadioButton radiobtn = sender as RadioButton;
            if (radiobtn.Tag == null)
                return;
            string radioTag = radiobtn.Tag.ToString().ToUpper();
            if (radioTag == "NONE")
            {
                EnableLocation = false;
                VisibleBrowse = false;
                VisibleUserPasswrod = false;
                releaseMethod = 0;
            }
            else if (radioTag == "LOCAL")
            {
                EnableLocation = true;
                VisibleBrowse = true;
                VisibleUserPasswrod = false;
                releaseMethod = 1;
            }
            else if (radioTag == "HTTP")
            {
                EnableLocation = true;
                VisibleBrowse = false;
                VisibleUserPasswrod = false;
                releaseMethod = 2;
            }
            else if (radioTag == "FTP")
            {
                EnableLocation = true;
                VisibleBrowse = false;
                VisibleUserPasswrod = true;
                releaseMethod = 3;
            }
            else if (radioTag == "W32SHARE")
            {
                EnableLocation = true;
                VisibleBrowse = false;
                VisibleUserPasswrod = true;
                releaseMethod = 4;
            }

            if (releaseMethod == proInfo.pReleaseMethod)
            {
                txtLocation.Text = proInfo.pReleaseUrl;
                txtUserName.Text = proInfo.pUsername;
                txtPassword.Text = proInfo.pPassword;
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            url = txtLocation.Text.Trim();
            user = txtUserName.Text.Trim();
            pwd = txtPassword.Text.Trim();
            
            if (releaseMethod == 0)
            {//不发布                
                //保存工程信息
                proInfo.pReleaseMethod = releaseMethod;
                proInfo.pReleaseUrl = txtLocation.Text.Trim();
                proInfo.pUsername = txtUserName.Text.Trim();
                proInfo.pPassword = txtPassword.Text.Trim();
                string projectFolder = GlobalValue.MD5(proInfo.pFullPath);
                string proFolder = Path.Combine(GlobalValue.ProjectDataPath, projectFolder);
                XmlSerializeHelper.SaveXmlFormObject(proFolder + "\\" + GlobalValue.ProjectInfoName, proInfo);

                this.Close();
                return;
            }

            btnNext.Enabled = false;
            btnCancel.Enabled = false;

            if (worker.IsBusy)
                return;
            progressBar1.Value = 0;
            uploadSize = 0;
            
            worker.RunWorkerAsync();
        }

        private void FormRelease_Load(object sender, EventArgs e)
        {
            publishPath = proInfo.pFullPath.Substring(0, proInfo.pFullPath.LastIndexOf("\\"));
            publishPath += "\\" + proInfo.pReleaseFolder.Substring(0,proInfo.pReleaseFolder.LastIndexOf("\\")) + "\\publish\\";

            foreach (ReleaseFile file in releaseList.Files)
            {
                fileTotalSize += file.FileSize;
            }
            labelSize.Text = string.Format("总大小：{0}", GlobalValue.FormatFileSize(fileTotalSize));

            //显示以前的发布信息
            switch(proInfo.pReleaseMethod)
            {
                case 0:
                    radioNone.Checked = true;
                    RadioButton_CheckeChanged(radioNone, new EventArgs());
                    break;
                case 1:
                    radioLocalFolder.Checked = true;
                    RadioButton_CheckeChanged(radioLocalFolder, new EventArgs());
                    break;
                case 2:
                    radioHttp.Checked = true;
                    RadioButton_CheckeChanged(radioHttp, new EventArgs());
                    break;
                case 3:
                    radioFtp.Checked = true;
                    RadioButton_CheckeChanged(radioFtp, new EventArgs());
                    break;
                case 4:
                    radioW32share.Checked = true;
                    RadioButton_CheckeChanged(radioW32share, new EventArgs());
                    break;
                default:
                    radioNone.Checked = true;
                    RadioButton_CheckeChanged(radioNone, new EventArgs());
                    break;
            }
            txtLocation.Text = proInfo.pReleaseUrl;
            txtUserName.Text = proInfo.pUsername;
            txtPassword.Text = proInfo.pPassword;
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            //string url = txtLocation.Text.Trim();
            //string user = txtUserName.Text.Trim();
            //string pwd = txtPassword.Text.Trim();

            using (UploadHelper uploader = UploadHelperFactory.CreateInstance(releaseMethod, url, user, pwd))
            {                
                foreach (ReleaseFile file in releaseList.Files)
                {
                    try
                    {
                        uploader.UploadFile(publishPath + "\\" + releaseList.ReleaseVersion, url + "\\" + releaseList.ReleaseVersion, 
                            file.FileName, ref uploadSize, worker, fileTotalSize);
                    }
                    catch 
                    {
                        e.Result = file.FileName;
                        throw;
                    }                    
                }
                //upload releaselist.xml
                try
                {
                    uploader.UploadFile(publishPath, url, GlobalValue.ReleaseListName, ref uploadSize, worker, fileTotalSize);
                }
                catch
                {
                    e.Result = GlobalValue.ReleaseListName;
                    throw;
                }   
            }
        }

        private void worker_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnNext.Enabled = true;
            btnCancel.Enabled = true;
            //保存工程信息
            proInfo.pReleaseMethod = releaseMethod;
            proInfo.pReleaseUrl = url;
            proInfo.pUsername = user;
            proInfo.pPassword = pwd;
            string projectFolder = GlobalValue.MD5(proInfo.pFullPath);
            string proFolder = Path.Combine(GlobalValue.ProjectDataPath, projectFolder);
            XmlSerializeHelper.SaveXmlFormObject(proFolder + "\\" + GlobalValue.ProjectInfoName, proInfo);

            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                return;
            }
            MessageBox.Show("恭喜您，发布完成！");
            this.Close();
        }

        private void worker_ProgressBar(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            labelSize.Text = string.Format("{0}/{1}", 
                GlobalValue.FormatFileSize(uploadSize), GlobalValue.FormatFileSize(fileTotalSize));
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (releaseMethod == 1)
            {//本地发布
                if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    txtLocation.Text = folderBrowserDialog1.SelectedPath;
                }
            }
            //todo Windows共享方式，可以做浏览局域网内机器
        }
    }
}
